package models

import (
	"errors"
	"fmt"
	"reflect"
	"strings"
	"time"

	"gitee.com/lzqysoft/ga_wz_backend/libs"
	"gitee.com/lzqysoft/ga_wz_backend/libs/strtool"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type SfEngineerInstanceItem struct {
	Id                        string       `orm:"column(id);pk"`
	Remark                    string    `orm:"column(remark);null"`
	Status                    int       `orm:"column(status)"`
	Isdelete                  int       `orm:"column(isdelete)"`
	Ctime                     time.Time `orm:"column(ctime);type(timestamp with time zone)"`
	Creater                   string    `orm:"column(creater)"`
	Utime                     time.Time `orm:"column(utime);type(timestamp with time zone)"`
	Updater                   string    `orm:"column(updater)"`
	Seq                       int       `orm:"column(seq)"`
	Name                      string    `orm:"column(name);null"`
	Sex                       int       `orm:"column(sex);null"`
	Birth                     time.Time `orm:"column(birth);type(timestamp with time zone);null"`
	Xueli                     int       `orm:"column(xueli);null"`
	Xuelihuode                int       `orm:"column(xuelihuode);null"`
	Biyeyuanxiaojizhuanye     string    `orm:"column(biyeyuanxiaojizhuanye);null"`
	Biyeshijian               time.Time `orm:"column(biyeshijian);type(timestamp with time zone);null"`
	Gongzuoshijiandanwei      string    `orm:"column(gongzuoshijiandanwei);null"`
	Jishugongzuoshijiandanwei string    `orm:"column(jishugongzuoshijiandanwei);null"`
	Jaindingzige              int       `orm:"column(jaindingzige);null"`
	Xianzhuanye               string    `orm:"column(xianzhuanye);null"`
	Qudejishuzigeshijian      string    `orm:"column(qudejishuzigeshijian);null"`
	Suozaibumen               string    `orm:"column(suozaibumen);null"`
	Kancha                    int       `orm:"column(kancha);null"`
	DeptId                    string    `orm:"column(dept_id);null"`
	OrginizationId            string    `orm:"column(orginization_id);null"`
	OperateType               int       `orm:"column(operate_type)"`
	EngineerId                string    `orm:"column(engineer_id);null"`
	EngineerInstanceId        string    `orm:"column(engineer_instance_id);null"`
}

func (t *SfEngineerInstanceItem) TableName() string {
	return "sf_engineer_instance_item"
}

func init() {
	orm.RegisterModel(new(SfEngineerInstanceItem))
}

// AddSfEngineerInstanceItem insert a new SfEngineerInstanceItem into database and returns
// last inserted Id on success.
func AddSfEngineerInstanceItem(m *SfEngineerInstanceItem) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

// GetSfEngineerInstanceItemById retrieves SfEngineerInstanceItem by Id. Returns error if
// Id doesn't exist
func GetSfEngineerInstanceItemById(id string) (v *SfEngineerInstanceItem, err error) {
	o := orm.NewOrm()
	v = &SfEngineerInstanceItem{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

// GetAllSfEngineerInstanceItem retrieves all SfEngineerInstanceItem matches certain condition. Returns empty list if
// no records exist
func GetAllSfEngineerInstanceItem(query map[string]string, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(SfEngineerInstanceItem))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		if strings.Contains(k, "isnull") {
			qs = qs.Filter(k, (v == "true" || v == "1"))
		} else {
			qs = qs.Filter(k, v)
		}
	}
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, errors.New("Error: unused 'order' fields")
		}
	}

	var l []SfEngineerInstanceItem
	qs = qs.OrderBy(sortFields...)
	if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				ml = append(ml, v)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, nil
	}
	return nil, err
}

// UpdateSfEngineerInstanceItem updates SfEngineerInstanceItem by Id and returns error if
// the record to be updated doesn't exist
func UpdateSfEngineerInstanceItemById(m *SfEngineerInstanceItem) (err error) {
	o := orm.NewOrm()
	v := SfEngineerInstanceItem{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteSfEngineerInstanceItem deletes SfEngineerInstanceItem by Id and returns error if
// the record to be deleted doesn't exist
func DeleteSfEngineerInstanceItem(id string) (err error) {
	o := orm.NewOrm()
	v := SfEngineerInstanceItem{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&SfEngineerInstanceItem{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

// CreateSFEngineerAddFlow 创建流程
func CreateSFEngineerAddFlow(items []SfEngineerInstanceItem, user *User) error {
	o := orm.NewOrm()
	o.Begin()
	// 创建 engineer_instance
	if len(items) <= 0 {
		o.Rollback()
		return errors.New("error data")
	}
	if (items[0].EngineerInstanceId == "") {
		beego.Debug("items[0].EngineerInstanceId == ' ' ")
		dept, err := GetDeptById(items[0].DeptId)
		if err != nil {
			beego.Debug(err)
			o.Rollback()
			return err
		}
		operateType := strtool.GetSFEngineerOperateTypeStr(items[0].OperateType)

		var instance SfEngineerInstance
		instance.Id = libs.UUID()
		instance.Name = user.Abbr + "关于"+dept.Name+operateType+"技术人员的申请"
		//instance, err := GetSfEngineerInstanceById(items[0].)
		instance.DeptId = dept.Id
		instance.Updater = user.Abbr
		instance.Creater = user.Abbr
		instance.Utime = time.Now()
		instance.Ctime = time.Now()
		instance.Status =1
		instance.Optype = items[0].OperateType
		instance.OrginizationId = user.Organization.Id
		instance.UserId = user.Id
		instance.DeptName = dept.Name
		_, err = o.Insert(&instance)
		if err != nil {
			beego.Debug(err)
			o.Rollback()
			return err
		}
		beego.Debug(instance.Id)
		if len(items) > 1 {
			for k, _ := range items {
				items[k].Id = libs.UUID()
				items[k].Status = 1
				items[k].OrginizationId = user.Organization.Id
				items[k].EngineerInstanceId = instance.Id
				items[k].Creater = user.Abbr
				items[k].Updater = user.Abbr
				items[k].Ctime = time.Now()
				items[k].Utime = time.Now()
			}
			_, err = o.InsertMulti(len(items), items)
			if err != nil {
				beego.Debug(err)
				o.Rollback()
				return err
			}
		} else {

			for k, _ := range items {
				items[k].Status = 1
				items[k].OrginizationId = user.Organization.Id
				items[k].EngineerInstanceId = instance.Id
				items[k].Creater = user.Abbr
				items[k].Updater = user.Abbr
				items[k].Ctime = time.Now()
				items[k].Utime = time.Now()
				_, err = o.Insert(&items[k])
				beego.Debug(err)
				if err != nil {
					o.Rollback()
					return err
				}
			}
		}

		return o.Commit()
	} else {
		beego.Debug("!items[0].EngineerInstanceId == ' ' ")
		instance, err := GetSfEngineerInstanceById(items[0].EngineerInstanceId)
		if err != nil {
			o.Rollback()
			return err
		}
		err = DeleteInstanceItemByInstance(items[0].EngineerInstanceId)
		if err != nil {
			o.Rollback()
			return err
		}
		if len(items) > 1 {
			for k, _ := range items {
				items[k].Status = 1
				items[k].OrginizationId = user.Organization.Id
				items[k].EngineerInstanceId = instance.Id
				items[k].Creater = user.Abbr
				items[k].Updater = user.Abbr
				items[k].Ctime = time.Now()
				items[k].Utime = time.Now()
				items[k].Id = libs.UUID()
			}
			_, err = o.InsertMulti(len(items), items)
			if err != nil {
				beego.Debug(err)
				o.Rollback()
				return err
			}
		} else {
			for k, _ := range items {
				items[k].Status = 1
				items[k].OrginizationId = user.Organization.Id
				items[k].EngineerInstanceId = instance.Id
				items[k].Creater = user.Abbr
				items[k].Updater = user.Abbr
				items[k].Ctime = time.Now()
				items[k].Utime = time.Now()
				items[k].Id = libs.UUID()
				_, err = o.Insert(&items[k])
				if err != nil {
					beego.Debug(err)
					o.Rollback()
					return err
				}
			}
		}
		return o.Commit()
	}

}


func GetInstanceItemByInstanceId(instanceId string) ([]SfEngineerInstanceItem, error) {
	var items []SfEngineerInstanceItem
	o := orm.NewOrm()
	_, err := o.QueryTable(new(SfEngineerInstanceItem)).Filter("engineer_instance_id", instanceId).Filter("isdelete", 0).
		OrderBy("-ctime").All(&items)
	return items, err
}

func DeleteInstanceItemByInstance(instanceId string) error {
	beego.Debug("delete item's instance id is : ", instanceId)
	o := orm.NewOrm()
	//num ,err :=o.Delete(&SfEngineerInstanceItem{EngineerInstanceId:instanceId})
	//num, err := o.QueryTable(new(SfEngineerInstanceItem)).Filter("engineer_instance_id", "instanceId").Delete()
	_, err := o.Raw("DELETE FROM sf_engineer_instance_item t WHERE t.engineer_instance_id = ?", instanceId).
		Exec()
	//fmt.Printf("Affected Num: %s, %s", num, err)
	//fmt.Println("delete items nums: ", num)
	return err
}